package com.github.rpc4j.consumer.zk;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import com.github.rpc4j.common.ServiceRequest;
import com.github.rpc4j.consumer.core.Rpc4jConsumerConfig;
import com.netflix.curator.framework.CuratorFramework;
import com.netflix.curator.framework.CuratorFrameworkFactory;
import com.netflix.curator.retry.RetryNTimes;

public class ZkUtil {
	
	private final static Logger logger =  Logger.getLogger(ZkUtil.class);
	
	private Rpc4jConsumerConfig config;
	
	private static final String RPC4J_ROOT_PATH = "/rpc4j";
	
	private static final String RPC4J_SERVER_PATH = "servers";
	
	private static final String RPC4J_CONSUMER_PATH = "consumeres";
	
	private static final String RPC4J_SERVICE_PATH = "services";
	
	
	private CuratorFramework client = null;
	
	public ZkUtil(Rpc4jConsumerConfig config){
		this.config = config;
	}
	
	
	public void init(){
        try{
        	Rpc4jCuratorListener listener = new Rpc4jCuratorListener();
        	client = CuratorFrameworkFactory.builder().connectString(config.getZkServer()).namespace(RPC4J_ROOT_PATH).retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000))
			.connectionTimeoutMs(5000).build();
        	client.getCuratorListenable().addListener(listener);
        	client.start();
        	isNotExistCreate(RPC4J_CONSUMER_PATH,null,CreateMode.PERSISTENT);
        	isNotExistCreate(config.getId(),null,CreateMode.PERSISTENT);
        	client.checkExists().watched().inBackground().forPath(RPC4J_ROOT_PATH);
        	client.getChildren().watched().inBackground().forPath(RPC4J_ROOT_PATH);
        	client.getCuratorListenable()
        	
        }catch(Exception e){
	    	logger.error(e);
		}finally{
			
		}
	}
	
	
	
	public void isNotExistCreate(String path,byte[] data,CreateMode mode){
		try{
		    Stat stat = client.checkExists().forPath(path);
		    if(stat==null){
		    	client.create().withMode(mode).forPath(path,data);
		    }
		}catch(Exception e){
	    	logger.error(e);
		}finally{
			
		}
	}
	
	public List<String> getServiceRegServer(ServiceRequest request){
		String path = RPC4J_SERVICE_PATH + "/" + request.getInterfaceName();
		try{
			Stat stat = client.checkExists().forPath(path);
			if(stat==null){
				throw new RuntimeException("not service in cluser;service interface name:"+request.getInterfaceName());
			}
		    List<String> list = client.getChildren().forPath(path);
		    return list;
		}catch(Exception e){
	    	logger.error(e);
		}finally{
			
		}
		return null;
	}
	
	
	
	
	

}
